// 存储注册了content script的标签页ID
let registeredTabs = new Set();

// 监听标签页更新
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === 'complete') {
    registeredTabs.add(tabId);
  }
});

// 监听标签页关闭
chrome.tabs.onRemoved.addListener((tabId) => {
  registeredTabs.delete(tabId);
});

// 安装时创建菜单
chrome.runtime.onInstalled.addListener(() => {
  try {
    chrome.contextMenus.create({
      id: "convertToMarkdown",
      title: "转为Markdown",
      contexts: ["selection"]
    });
  } catch (err) {
    console.error('创建菜单失败:', err);
  }
});

// 处理右键菜单点击
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
  if (info.menuItemId === "convertToMarkdown") {
    try {
      // 检查页面是否可访问
      if (!tab.url.startsWith('http')) {
        console.error('不支持的页面类型');
        return;
      }

      // 注入content script
      await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        files: ['content.js']
      });

      // 等待一小段时间确保脚本加载完成
      await new Promise(resolve => setTimeout(resolve, 100));

      // 发送消息
      await chrome.tabs.sendMessage(tab.id, {
        action: "convertToMarkdown",
        text: info.selectionText
      });
    } catch (err) {
      console.error('操作失败:', err);
    }
  }
}); 